package com.why.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.why.pojo.User;
import com.why.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

/**
 * @author new wei
 * @date 2022/5/16 11:16
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("auth")
    public String auth(String code,HttpServletResponse response){
        String url="https://gitee.com/oauth/token?grant_type=authorization_code&";
        //POST请求
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        paramMap.put("client_id", "dd05f42c61ee4e695b1d54c77437ea15cbe7c1b024d758036147a64cd4218415");
        paramMap.put("redirect_uri", "http://localhost:8080/user/auth");
        paramMap.put("client_secret", "057d79cb632a5f734a93d3cfc89609caf55a0cfcb4f86cbfad9d0258062a8a1c");

        String token = HttpUtil.post(url, paramMap);
        JSONObject jsonObject = JSON.parseObject(token);
        Object access_token = jsonObject.get("access_token");
        String url2="https://gitee.com/api/v5/user?access_token="+access_token;
        JSONObject jsonObject1 = JSON.parseObject(HttpUtil.get(url2));
        Object name = jsonObject1.get("name");
        User user = userService.getUser(name + "");
        if (null==user){
            user=new User();
            user.setUname(name+"");
            userService.addUser(user);
        }
        // 密钥
        byte[] key = "1234567890".getBytes();

        String tokenGit = JWT.create()
                .setPayload("uname", user.getUname())
                .setPayload("uid", user.getUid())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(), DateField.MINUTE,30))
                .sign();
        Cookie cookie = new Cookie("LOGIN_TOKEN",tokenGit);
        cookie.setPath("/");
        cookie.setMaxAge(60*30);
        response.addCookie(cookie);
        return "redirect:/manage/list";
    }

    @GetMapping("toLogin")
    public String toLogin(Model model){
        model.addAttribute("user",new User());
        return "login";
    }
    @PostMapping("login")
    public String login(@Validated User user, BindingResult result, HttpServletResponse response){
        if (result.hasErrors()){
            return "login";
        }
        User u1=userService.getUser(user.getUname());
        if (null==u1){
            result.rejectValue("uname","","用户不存在");
            return "login";
        }
        if (!user.getUpass().equals(u1.getUpass())){
            result.rejectValue("upass","","密码错误");
            return "login";
        }
        // 密钥
        byte[] key = "1234567890".getBytes();

        String token = JWT.create()
                .setPayload("uname", u1.getUname())
                .setPayload("uid", u1.getUid())
                .setKey(key)
                .setExpiresAt(DateUtil.offset(new Date(), DateField.MINUTE,20))
                .sign();
        Cookie cookie = new Cookie("LOGIN_TOKEN",token);
        cookie.setPath("/");
        cookie.setMaxAge(60*30);
        response.addCookie(cookie);
        return "redirect:/manage/list";
    }

}
